﻿using B.S.GridManage.Api.Read.Application.Command.LogicalGrid;
using B.S.GridManage.Api.Read.Dtos;
using B.S.GridManage.Domain.Entities;
using B.S.GridManage.ErrorCode;
using B.S.GridManage.Infrastructure.Interface;
using MediatR;

namespace B.S.GridManage.Api.Read.Application.Handler.LogicalGrid
{
    /// <summary>
    /// 查询逻辑网格的处理类
    /// </summary>
    public class GetLogicalGridHandler : IRequestHandler<GetLogicalGridCommand, ApiPaging<LogicalDto>>
    {
        private readonly IBaseRepository<LogicalGridModel> logicalRepo;

        public GetLogicalGridHandler(IBaseRepository<LogicalGridModel> logicalRepo)
        {
            this.logicalRepo = logicalRepo;
        }

        /// <summary>
        /// 查询逻辑网格的处理方法
        /// </summary>
        /// <param name="request">查询命令</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>响应包装类</returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiPaging<LogicalDto>> Handle(GetLogicalGridCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<LogicalDto> res = new ApiPaging<LogicalDto>();
            var logical = logicalRepo.GetAll().Where(x => !x.IsDeleted);
            var logicalParent = logicalRepo.GetAll().Where(x => !x.IsDeleted);


            //      /// <summary>
            //      /// 网格名称
            //      /// </summary>
            //public string? GridName { get; set; }
            ///// <summary>
            ///// 上级网格名称
            ///// </summary>
            //public string? ParentGridName { get; set; }


            //条件判断
            if (!string.IsNullOrEmpty(request.GridName))
            {
                logical = logical.Where(x => x.GridName.Contains(request.GridName));
            }

            if (!string.IsNullOrEmpty(request.GridName))
            {
                logicalParent = logicalParent.Where(x => x.GridName.Contains(request.ParentGridName));
            }

            var linq = from l in logical
                       join lp in logicalParent on l.ParentCode equals lp.GridCode
                       select new LogicalDto
                       {
                           Id = l.Id,
                           GridCode = l.GridCode,
                           ParentCode = l.ParentCode,
                           DepartmentName = l.DepartmentName,
                           GridName = l.GridName,
                           ParentName = lp.GridName
                       };

            res.TotalCount = linq.Count();
            res.PageDatas = linq.OrderByDescending(x => x.Id).Skip(((request.PageIndex-1)*request.PageSize)).Take(request.PageSize).ToList();
            res.Msg = "查询列表成功!";
            res.Code = ApiEnum.Success;
            return res;


        }
    }
}
